package com.ncucoder.soms.filter;

import com.ncucoder.soms.util.JwtTokenUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @date 2019-07-09
 **/
public class RolesAuthFilter extends BasicHttpAuthenticationFilter {

    private Logger logger = LoggerFactory.getLogger(RolesAuthFilter.class);

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        HttpServletRequest req = (HttpServletRequest) request;
        // 获取到jwtToken
        String jwtToken = req.getHeader(JwtTokenUtils.REQUEST_TOKEN_HEADER).replace(JwtTokenUtils.TOKEN_PREFIX, "");
        // 获取保存在jwtToken中的roles
        String role = JwtTokenUtils.getRole(jwtToken);

        // 获取到配置文件(spring-shiro.xml)中需要的roles
        // 本项目一个用户只有一个角色, 所以这里的roles的长度只能是0或者1
        String[] rolesArray = (String[]) mappedValue;
        if (rolesArray == null || rolesArray.length == 0) {
            //no roles specified, so nothing to check - allow access.
            return true;
        }
        if (role != null && !"".equals(role)) {
            return role.equals(rolesArray[0]);
        } else {
            return false;
        }

    }
}
